﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace Siva.CBC.Barnacle.ashx
{
    /// <summary>
    /// ioscommonHandler 的摘要说明
    /// </summary>
    public class ioscommonHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //1.接收参数
            //string content = context.Request.Form["content"];
            Stream inputStream = context.Request.InputStream;
            byte[] buffer = new byte[inputStream.Length];
            inputStream.Read(buffer, 0, buffer.Length);
            string content = Encoding.UTF8.GetString(buffer);

            //context.Response.Write(content == "m1h5UyYuqkrPGInbD4vDaQ==");

            //return;

            //密钥
            Byte[] encryptedBytes = Convert.FromBase64String(content);
            string Key = "ioscar-common123";
            string result = string.Empty;


            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(Key);
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
            result = UTF8Encoding.UTF8.GetString(resultArray);

            context.Response.Write(result);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private static byte[] ReadAllBytes(Stream input)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                input.CopyTo(ms); // 将CryptoStream中的数据复制到内存流中，以便读取明文数据。这一步在ECB模式下是多余的，因为不需要填充。但在其他模式下可能不是。
                return ms.ToArray(); // 返回解密后的明文数据。注意，实际上在ECB模式下解密后不需要进一步处理，因为数据已经是明文了。这里的处理是为了演示完整性。
            }
        }

    }
}